const UI = {
    // 页面类型常量
    PAGE_TYPES: {
        JOB_LIST: 'jobList',
        CHAT: 'chat'
    },

    currentPageType: null,

    init() {
        this.currentPageType = location.pathname.includes('/chat')
            ? this.PAGE_TYPES.CHAT
            : this.PAGE_TYPES.JOB_LIST;
        this._applyTheme();
        this.createControlPanel();
        this.createMiniIcon();
    },

    createControlPanel() {
        if (document.getElementById('boss-pro-panel')) {
            document.getElementById('boss-pro-panel').remove();
        }

        elements.panel = this._createPanel();

        const header = this._createHeader();
        const controls = this._createPageControls();
        elements.log = this._createLogger();
        const footer = this._createFooter();

        elements.panel.append(header, controls, elements.log, footer);
        document.body.appendChild(elements.panel);
        this._makeDraggable(elements.panel);
    },

    _applyTheme() {
        CONFIG.COLORS = this.currentPageType === this.PAGE_TYPES.JOB_LIST
            ? this.THEMES.JOB_LIST
            : this.THEMES.CHAT;

        // 设置CSS变量
        document.documentElement.style.setProperty('--primary-color', CONFIG.COLORS.primary);
        document.documentElement.style.setProperty('--secondary-color', CONFIG.COLORS.secondary);
        document.documentElement.style.setProperty('--accent-color', CONFIG.COLORS.accent);
        document.documentElement.style.setProperty('--neutral-color', CONFIG.COLORS.neutral);
    },

    THEMES: {
        JOB_LIST: {
            primary: '#4285f4',
            secondary: '#f5f7fa',
            accent: '#e8f0fe',
            neutral: '#6b7280'
        },
        CHAT: {
            primary: '#34a853',
            secondary: '#f0fdf4',
            accent: '#dcfce7',
            neutral: '#6b7280'
        }
    },

    _createPanel() {
        const panel = document.createElement('div');
        panel.id = 'boss-pro-panel';
        panel.className = this.currentPageType === this.PAGE_TYPES.JOB_LIST
            ? 'boss-joblist-panel'
            : 'boss-chat-panel';

        // 基础样式
        const baseStyles = `
            position: fixed;
            top: 36px;
            right: 24px;
            width: clamp(300px, 80vw, 400px);
            border-radius: 16px;
            padding: 18px;
            font-family: 'Segoe UI', system-ui, sans-serif;
            z-index: 2147483647;
            display: flex;
            flex-direction: column;
            transition: all 0.3s ease;
            background: #ffffff;
            box-shadow: 0 10px 25px rgba(var(--primary-rgb), 0.15);
            border: 1px solid var(--accent-color);
            cursor: default;
        `;

        panel.style.cssText = baseStyles;

        // 设置RGB颜色变量
        const rgbColor = this._hexToRgb(CONFIG.COLORS.primary);
        document.documentElement.style.setProperty('--primary-rgb', rgbColor);

        return panel;
    },

    _createHeader() {
        const header = document.createElement('div');
        header.className = this.currentPageType === this.PAGE_TYPES.JOB_LIST
            ? 'boss-header'
            : 'boss-chat-header';

        header.style.cssText = `
            display: flex;
            justify-content: space-between;
            align-items: center;
            padding: 0 10px 15px;
            margin-bottom: 15px;
            border-bottom: 1px solid var(--accent-color);
        `;

        const title = this._createTitle();

        // 创建按钮容器
        const buttonContainer = document.createElement('div');
        buttonContainer.style.cssText = `
            display: flex;
            gap: 8px;
        `;

        // 按钮标题
        const buttonTitles = this.currentPageType === this.PAGE_TYPES.JOB_LIST
            ? { clear: '清空日志', settings: '插件设置', close: '最小化海投面板' }
            : { clear: '清空聊天记录', settings: 'AI人设设置', close: '最小化聊天面板' };

        // 添加清空日志按钮
        const clearLogBtn = this._createIconButton('🗑', () => {
            elements.log.innerHTML = `<div style="color:var(--neutral-color); margin-bottom:8px;">欢迎使用海投助手，愿您在求职路上一帆风顺！</div>`;
        }, buttonTitles.clear);

        // 添加设置按钮
        const settingsBtn = this._createIconButton('⚙', () => {
            showSettingsDialog();
        }, buttonTitles.settings);

        // 添加最小化按钮
        const closeBtn = this._createIconButton('✕', () => {
            state.isMinimized = true;
            elements.panel.style.transform = 'translateY(160%)';
            elements.miniIcon.style.display = 'flex';
        }, buttonTitles.close);

        buttonContainer.append(clearLogBtn, settingsBtn, closeBtn);
        header.append(title, buttonContainer);
        return header;
    },

    _createTitle() {
        const title = document.createElement('div');
        title.style.display = 'flex';
        title.style.alignItems = 'center';
        title.style.gap = '10px';

        // SVG图标
        const customSvg = `
        <svg viewBox="0 0 1024 1024" xmlns="http://www.w3.org/2000/svg" 
             style="width: 100%; height: 100%; fill: white;">
            <path d="M512 116.032a160 160 0 0 1 52.224 311.232v259.008c118.144-22.272 207.552-121.088 207.552-239.36 0-25.152 21.568-45.568 48.128-45.568 26.624 0 48.128 20.416 48.128 45.632 0 184.832-158.848 335.232-354.048 335.232S160 631.808 160 446.976c0-25.152 21.568-45.632 48.128-45.632 26.624 0 48.128 20.48 48.128 45.632 0 118.144 89.088 216.96 206.976 239.296V428.416A160.064 160.064 0 0 1 512 116.032z m0 96a64 64 0 1 0 0 128 64 64 0 0 0 0-128z m-36.672 668.48l-21.888-19.584a17.92 17.92 0 0 0-24.64 0l-21.952 19.584a56.32 56.32 0 0 1-77.504 0l-21.952-19.584a17.92 17.92 0 0 0-24.64 0l-28.288 25.6c-9.6 8.704-23.36 6.4-30.72-4.992a29.696 29.696 0 0 1 4.16-36.672l28.352-25.6a56.32 56.32 0 0 1 77.568 0l21.888 19.584a17.92 17.92 0 0 0 24.704 0l21.824-19.52a56.32 56.32 0 0 1 77.568 0l21.888 19.52a17.92 17.92 0 0 0 24.64 0l21.952-19.52a56.32 56.32 0 0 1 77.504 0l21.952 19.52a17.92 17.92 0 0 0 24.64 0l21.824-19.52a56.32 56.32 0 0 1 77.632 0l21.824 19.52c9.664 8.704 11.52 25.152 4.224 36.672-7.296 11.52-21.12 13.696-30.72 4.992l-21.888-19.584a17.92 17.92 0 0 0-24.64 0l-21.888 19.584a56.32 56.32 0 0 1-77.568 0l-21.888-19.584a17.92 17.92 0 0 0-24.64 0l-21.888 19.584a57.408 57.408 0 0 1-38.656 15.488 58.176 58.176 0 0 1-38.784-15.488z" />
        </svg>
    `;

        // 标题配置
        const titleConfig = this.currentPageType === this.PAGE_TYPES.JOB_LIST
            ? { main: `<span style="color:var(--primary-color);">BOSS</span>海投助手`, sub: '高效求职 · 智能匹配' }
            : { main: `<span style="color:var(--primary-color);">BOSS</span>智能聊天`, sub: '智能对话 · 高效沟通' };

        title.innerHTML = `
        <div style="
            width: 40px;
            height: 40px;
            background: var(--primary-color);
            border-radius: 10px;
            display: flex;
            justify-content: center;
            align-items: center;
            color: white;
            font-weight: bold;
            box-shadow: 0 2px 8px rgba(var(--primary-rgb), 0.3);
        ">
            ${customSvg}
        </div>
        <div>
            <h3 style="
                margin: 0;
                color: #2c3e50;
                font-weight: 600;
                font-size: 1.2rem;
            ">
                ${titleConfig.main}
            </h3>
            <span style="
                font-size:0.8em;
                color:var(--neutral-color);
            ">
                ${titleConfig.sub}
            </span>
        </div>
    `;

        return title;
    },

    // 创建页面控制区域
    _createPageControls() {
        if (this.currentPageType === this.PAGE_TYPES.JOB_LIST) {
            return this._createJobListControls();
        } else {
            return this._createChatControls();
        }
    },

    // 创建职位列表页面控制区域
    _createJobListControls() {
        const container = document.createElement('div');
        container.className = 'boss-joblist-controls';
        container.style.marginBottom = '15px';
        container.style.padding = '0 10px';

        // 筛选条件区域
        const filterContainer = this._createFilterContainer();

        elements.controlBtn = this._createTextButton(
            '启动海投',
            'var(--primary-color)',
            () => {
                toggleProcess();
            }
        );

        // 居中控制按钮
        const btnContainer = document.createElement('div');
        btnContainer.style.cssText = `
            display: flex;
            justify-content: center;
            width: 100%;
        `;
        btnContainer.appendChild(elements.controlBtn);

        container.append(filterContainer, btnContainer);
        return container;
    },

    // 创建聊天页面控制区域
    _createChatControls() {
        const container = document.createElement('div');
        container.className = 'boss-chat-controls';
        container.style.marginBottom = '15px';
        container.style.padding = '0 10px';

        // 人设和模板选择
        const configRow = document.createElement('div');
        configRow.style.cssText = `
            display: flex;
            gap: 10px;
            margin-bottom: 15px;
        `;

        // 动态获取AI人设选项，包括默认选项和用户自定义选项
        const getPersonaOptions = () => {
            // 默认角色选项
            const defaultOptions = [
                { value: 'default', text: '默认' },
                { value: 'tech', text: 'Ai人设1' },
                { value: 'product', text: 'Ai人设2' },
                { value: 'marketing', text: 'Ai人设3' }
            ];

            // 获取用户自定义角色
            const customPersonas = settings.customPersonas || [];

            // 合并默认选项和自定义选项
            return [...defaultOptions, ...customPersonas];
        };

        const personaCol = this._createSelectControl('AI人设：', 'ai-persona-selector', getPersonaOptions());

        const templateCol = this._createSelectControl('回复模板：', 'reply-template-selector', [
            { value: 'standard', text: '标准' },
            { value: 'brief', text: '简洁' },
            { value: 'detailed', text: '详细' }
        ]);

        elements.personaSelector = personaCol.querySelector('select');
        configRow.append(personaCol, templateCol);

        elements.controlBtn = this._createTextButton(
            '开始智能聊天',
            'var(--primary-color)',
            () => {
                toggleChatProcess();
            }
        );

        // 居中控制按钮
        const btnContainer = document.createElement('div');
        btnContainer.style.cssText = `
            display: flex;
            justify-content: center;
            width: 100%;
        `;
        btnContainer.appendChild(elements.controlBtn);

        container.append(configRow, btnContainer);
        return container;
    },

    // 创建筛选容器
    _createFilterContainer() {
        const filterContainer = document.createElement('div');
        filterContainer.style.cssText = `
            background: var(--secondary-color);
            border-radius: 12px;
            padding: 15px;
            margin-bottom: 15px;
        `;

        // 岗位和地点筛选使用两列布局
        const filterRow = document.createElement('div');
        filterRow.style.cssText = `
            display: flex;
            gap: 10px;
            margin-bottom: 12px;
        `;

        // 职位名包含 和 工作地包含
        const includeFilterCol = this._createInputControl('职位名包含：', 'include-filter', '如：前端,开发');
        const locationFilterCol = this._createInputControl('工作地包含：', 'location-filter', '如：杭州,滨江');

        elements.includeInput = includeFilterCol.querySelector('input');
        elements.locationInput = locationFilterCol.querySelector('input');

        filterRow.append(includeFilterCol, locationFilterCol);

        // 加海投服务QQ群按钮
        const joinGroupBtn = document.createElement('button');
        joinGroupBtn.className = 'boss-advanced-filter-btn';
        joinGroupBtn.innerHTML = '<i class="fa fa-sliders"></i> 海投服务群';
        joinGroupBtn.style.cssText = `
            width: 100%;
            padding: 8px 10px;
            background: white;
            color: var(--primary-color);
            border: 1px solid var(--primary-color);
            border-radius: 8px;
            cursor: pointer;
            font-size: 14px;
            text-align: center;
            transition: all 0.2s ease;
            display: flex;
            justify-content: center;
            align-items: center;
            gap: 5px;
        `;

        joinGroupBtn.addEventListener('click', () => {
            window.open('https://qm.qq.com/q/ZNOz2ZZb6S', '_blank');
        });

        joinGroupBtn.addEventListener('mouseenter', () => {
            joinGroupBtn.style.backgroundColor = 'var(--primary-color)';
            joinGroupBtn.style.color = 'white';
        });

        joinGroupBtn.addEventListener('mouseleave', () => {
            joinGroupBtn.style.backgroundColor = 'white';
            joinGroupBtn.style.color = 'var(--primary-color)';
        });

        filterContainer.append(filterRow, joinGroupBtn);
        return filterContainer;
    },

    // 创建输入控件
    _createInputControl(labelText, id, placeholder) {
        const controlCol = document.createElement('div');
        controlCol.style.cssText = 'flex: 1;';

        const label = document.createElement('label');
        label.textContent = labelText;
        label.style.cssText = 'display:block; margin-bottom:5px; font-weight: 500; color: #333; font-size: 0.9rem;';

        const input = document.createElement('input');
        input.id = id;
        input.placeholder = placeholder;
        input.className = 'boss-filter-input';
        input.style.cssText = `
            width: 100%;
            padding: 8px 10px;
            border-radius: 8px;
            border: 1px solid #d1d5db;
            font-size: 14px;
            box-shadow: 0 1px 2px rgba(0,0,0,0.05);
            transition: all 0.2s ease;
        `;

        controlCol.append(label, input);
        return controlCol;
    },

    // 创建选择控件
    _createSelectControl(labelText, id, options) {
        const controlCol = document.createElement('div');
        controlCol.style.cssText = 'flex: 1;';

        const label = document.createElement('label');
        label.textContent = labelText;
        label.style.cssText = 'display:block; margin-bottom:5px; font-weight: 500; color: #333; font-size: 0.9rem;';

        const select = document.createElement('select');
        select.id = id;
        select.style.cssText = `
            width: 100%;
            padding: 8px 10px;
            border-radius: 8px;
            border: 1px solid #d1d5db;
            font-size: 14px;
            background: white;
            color: #333;
            box-shadow: 0 1px 2px rgba(0,0,0,0.05);
            transition: all 0.2s ease;
        `;

        // 添加选项
        options.forEach(option => {
            const opt = document.createElement('option');
            opt.value = option.value;
            opt.textContent = option.text;
            select.appendChild(opt);
        });

        controlCol.append(label, select);
        return controlCol;
    },

    // 日志区域
    _createLogger() {
        const log = document.createElement('div');
        log.id = 'pro-log';
        log.className = this.currentPageType === this.PAGE_TYPES.JOB_LIST
            ? 'boss-joblist-log'
            : 'boss-chat-log';

        const height = this.currentPageType === this.PAGE_TYPES.JOB_LIST ? '180px' : '220px';

        log.style.cssText = `
            height: ${height};
            overflow-y: auto;
            background: var(--secondary-color);
            border-radius: 12px;
            padding: 12px;
            font-size: 13px;
            line-height: 1.5;
            margin-bottom: 15px;
            margin-left: 10px;
            margin-right: 10px;
            transition: all 0.3s ease;
            user-select: text;
            scrollbar-width: thin;
            scrollbar-color: var(--primary-color) var(--secondary-color);
        `;

        // 自定义滚动条样式
        log.innerHTML += `
            <style>
                #pro-log::-webkit-scrollbar {
                    width: 6px;
                }
                #pro-log::-webkit-scrollbar-track {
                    background: var(--secondary-color);
                    border-radius: 4px;
                }
                #pro-log::-webkit-scrollbar-thumb {
                    background-color: var(--primary-color);
                    border-radius: 4px;
                }
            </style>
        `;

        return log;
    },

    // 面板页脚
    _createFooter() {
        const footer = document.createElement('div');
        footer.className = this.currentPageType === this.PAGE_TYPES.JOB_LIST
            ? 'boss-joblist-footer'
            : 'boss-chat-footer';

        footer.style.cssText = `
            text-align: center;
            font-size: 0.8em;
            color: var(--neutral-color);
            padding-top: 15px;
            border-top: 1px solid var(--accent-color);
            margin-top: auto;
            padding: 15px;
        `;

        const statsContainer = document.createElement('div');
        statsContainer.style.cssText = `
            display: flex;
            justify-content: space-around;
            margin-bottom: 15px;
        `;

        footer.append(statsContainer, document.createTextNode('© 2025 Yangshengzhou · All Rights Reserved'));
        return footer;
    },

    // 文本按钮
    _createTextButton(text, bgColor, onClick) {
        const btn = document.createElement('button');
        btn.className = 'boss-btn';
        btn.textContent = text;
        btn.style.cssText = `
            width: 100%;
            max-width: 320px;
            padding: 10px 16px;
            background: ${bgColor};
            color: #fff;
            border: none;
            border-radius: 10px;
            cursor: pointer;
            font-size: 15px;
            font-weight: 500;
            transition: all 0.3s ease;
            display: flex;
            justify-content: center;
            align-items: center;
            box-shadow: 0 4px 10px rgba(0,0,0,0.1);
        `;

        this._addButtonHoverEffects(btn);
        btn.addEventListener('click', onClick);

        return btn;
    },

    // 图标按钮
    _createIconButton(icon, onClick, title) {
        const btn = document.createElement('button');
        btn.className = 'boss-icon-btn';
        btn.innerHTML = icon;
        btn.title = title;
        btn.style.cssText = `
            width: 32px;
            height: 32px;
            border-radius: 50%;
            border: none;
            background: ${this.currentPageType === this.PAGE_TYPES.JOB_LIST ? 'var(--accent-color)' : 'var(--accent-color)'};
            cursor: pointer;
            font-size: 16px;
            transition: all 0.2s ease;
            display: flex;
            justify-content: center;
            align-items: center;
            color: var(--primary-color);
        `;

        btn.addEventListener('click', onClick);
        btn.addEventListener('mouseenter', () => {
            btn.style.backgroundColor = 'var(--primary-color)';
            btn.style.color = '#fff';
            btn.style.transform = 'scale(1.1)';
        });

        btn.addEventListener('mouseleave', () => {
            btn.style.backgroundColor = this.currentPageType === this.PAGE_TYPES.JOB_LIST ? 'var(--accent-color)' : 'var(--accent-color)';
            btn.style.color = 'var(--primary-color)';
            btn.style.transform = 'scale(1)';
        });

        return btn;
    },

    // 添加按钮悬停效果
    _addButtonHoverEffects(btn) {
        btn.addEventListener('mouseenter', () => {
            btn.style.transform = 'translateY(-2px)';
            btn.style.boxShadow = `0 6px 15px rgba(var(--primary-rgb), 0.3)`;
        });

        btn.addEventListener('mouseleave', () => {
            btn.style.transform = 'translateY(0)';
            btn.style.boxShadow = '0 4px 10px rgba(0,0,0,0.1)';
        });
    },

    // 设置面板可拖动功能
    _makeDraggable(panel) {
        const header = panel.querySelector('.boss-header, .boss-chat-header');

        if (!header) return;

        header.style.cursor = 'move';

        let isDragging = false;
        let startX = 0, startY = 0;
        let initialX = panel.offsetLeft, initialY = panel.offsetTop;

        header.addEventListener('mousedown', (e) => {
            isDragging = true;
            startX = e.clientX;
            startY = e.clientY;
            initialX = panel.offsetLeft;
            initialY = panel.offsetTop;
            panel.style.transition = 'none';
            panel.style.zIndex = '2147483647';
        });

        document.addEventListener('mousemove', (e) => {
            if (!isDragging) return;

            const dx = e.clientX - startX;
            const dy = e.clientY - startY;

            panel.style.left = `${initialX + dx}px`;
            panel.style.top = `${initialY + dy}px`;
            panel.style.right = 'auto';
        });

        document.addEventListener('mouseup', () => {
            if (isDragging) {
                isDragging = false;
                panel.style.transition = 'all 0.3s ease';
                panel.style.zIndex = '2147483646';
            }
        });
    },

    // 最小化图标
    createMiniIcon() {
        elements.miniIcon = document.createElement('div');
        elements.miniIcon.style.cssText = `
        width: ${CONFIG.MINI_ICON_SIZE || 48}px;
        height: ${CONFIG.MINI_ICON_SIZE || 48}px;
        position: fixed;
        bottom: 40px;
        left: 40px;
        background: var(--primary-color);
        border-radius: 50%;
        box-shadow: 0 6px 16px rgba(var(--primary-rgb), 0.4);
        cursor: pointer;
        display: none;
        justify-content: center;
        align-items: center;
        color: #fff;
        z-index: 2147483647;
        transition: all 0.3s ease;
        overflow: hidden;
        padding: 8px; /* 添加内边距 */
    `;

        // SVG图标
        const customSvg = `
        <svg viewBox="0 0 1024 1024" xmlns="http://www.w3.org/2000/svg" 
             style="width: 100%; height: 100%; fill: white;">
            <path d="M512 116.032a160 160 0 0 1 52.224 311.232v259.008c118.144-22.272 207.552-121.088 207.552-239.36 0-25.152 21.568-45.568 48.128-45.568 26.624 0 48.128 20.416 48.128 45.632 0 184.832-158.848 335.232-354.048 335.232S160 631.808 160 446.976c0-25.152 21.568-45.632 48.128-45.632 26.624 0 48.128 20.48 48.128 45.632 0 118.144 89.088 216.96 206.976 239.296V428.416A160.064 160.064 0 0 1 512 116.032z m0 96a64 64 0 1 0 0 128 64 64 0 0 0 0-128z m-36.672 668.48l-21.888-19.584a17.92 17.92 0 0 0-24.64 0l-21.952 19.584a56.32 56.32 0 0 1-77.504 0l-21.952-19.584a17.92 17.92 0 0 0-24.64 0l-28.288 25.6c-9.6 8.704-23.36 6.4-30.72-4.992a29.696 29.696 0 0 1 4.16-36.672l28.352-25.6a56.32 56.32 0 0 1 77.568 0l21.888 19.584a17.92 17.92 0 0 0 24.704 0l21.824-19.52a56.32 56.32 0 0 1 77.568 0l21.888 19.52a17.92 17.92 0 0 0 24.64 0l21.952-19.52a56.32 56.32 0 0 1 77.504 0l21.952 19.52a17.92 17.92 0 0 0 24.64 0l21.824-19.52a56.32 56.32 0 0 1 77.632 0l21.824 19.52c9.664 8.704 11.52 25.152 4.224 36.672-7.296 11.52-21.12 13.696-30.72 4.992l-21.888-19.584a17.92 17.92 0 0 0-24.64 0l-21.888 19.584a56.32 56.32 0 0 1-77.568 0l-21.888-19.584a17.92 17.92 0 0 0-24.64 0l-21.888 19.584a57.408 57.408 0 0 1-38.656 15.488 58.176 58.176 0 0 1-38.784-15.488z" />
        </svg>
    `;

        elements.miniIcon.innerHTML = customSvg;

        // 添加悬停效果
        elements.miniIcon.addEventListener('mouseenter', () => {
            elements.miniIcon.style.transform = 'scale(1.1)';
            elements.miniIcon.style.boxShadow = `0 8px 20px rgba(var(--primary-rgb), 0.5)`;
        });

        elements.miniIcon.addEventListener('mouseleave', () => {
            elements.miniIcon.style.transform = 'scale(1)';
            elements.miniIcon.style.boxShadow = `0 6px 16px rgba(var(--primary-rgb), 0.4)`;
        });

        // 添加点击事件
        elements.miniIcon.addEventListener('click', () => {
            state.isMinimized = false;
            elements.panel.style.transform = 'translateY(0)';
            elements.miniIcon.style.display = 'none';
        });

        document.body.appendChild(elements.miniIcon);
    },

    // 十六进制颜色转RGB
    _hexToRgb(hex) {
        // 去除可能存在的#前缀
        hex = hex.replace('#', '');

        // 解析RGB值
        const r = parseInt(hex.substring(0, 2), 16);
        const g = parseInt(hex.substring(2, 4), 16);
        const b = parseInt(hex.substring(4, 6), 16);

        return `${r}, ${g}, ${b}`;
    }
};


// 初始化UI
document.addEventListener('DOMContentLoaded', () => {
    UI.init();
});
